<template>
  <div>
    
    <el-row class="toolbar">
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="学员名称">
          <el-input v-model="queryForm.name" placeholder="学员名称"></el-input>
        </el-form-item>
   
        <el-form-item>
          <el-button type="primary" @click="getListStu(queryForm)">查询</el-button>
          <el-button @click="resetStuQuery">重置</el-button>
          <el-button type="primary" plain @click="openAddStuDialog">添加</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="openCheckStu">审核学员</el-button>
        <el-button type="primary" @click="openUpdateStu">批量导入学员</el-button>
        <el-button type="primary" @click="downlaod">下载批量导入学员模板</el-button>
      </div>
    </el-row>
    <el-row>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column prop="stuName" label="姓名"/>
        <el-table-column prop="currentGrade" label="年级">
          <template slot-scope="scope">{{ scope.row.currentGrade || '-' }}</template>
        </el-table-column>
        <el-table-column prop="fromPlace" label="籍贯">
          <template slot-scope="scope">{{ scope.row.fromPlace || '-' }}</template>
        </el-table-column>
        <el-table-column prop="parentPhone" label="家长电话">
          <template slot-scope="scope">{{ scope.row.parentPhone || '-' }}</template>
        </el-table-column>
        <el-table-column prop="isFirst" label="是否新生">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.isFirst == '1'">否</el-tag>
            <el-tag v-else>是</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.status == '0'">未审核</el-tag>
            <el-tag v-else-if="scope.row.status == '1'">已审核</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="250">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" type="text">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="text">删除</el-button>
            <el-button @click="handleDetail(scope.row)" type="text">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background    
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[4,5,6,7]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" 
        style="margin-top: 30px;"/>
    </el-row>
    

    <el-dialog :visible.sync="stuDialogVisible" width="400px" :title="mode=='edit'?'编辑学员':'添加学员'" @closed="cancelDialog">
      <el-form :model="stuForm" label-position="left" label-width="90px">
        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="stuForm.stuName"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" v-if="mode == 'add'">
          <el-input v-model="stuForm.email"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="currentGrade">
          <el-input v-model="stuForm.currentGrade"></el-input>
        </el-form-item>
        <el-form-item label="籍贯" prop="fromPlace">
          <el-input v-model="stuForm.fromPlace"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone" v-if="mode == 'add'">
          <el-input v-model="stuForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="家长电话" prop="parentPhone">
          <el-input v-model="stuForm.parentPhone"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birthday" v-if="mode == 'add'">
            <el-date-picker
              v-model="stuForm.birthday"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="是否为新生" prop="isFirst">
            <el-select v-model="stuForm.isFirst" placeholder="请选择">
              <el-option
                v-for="item in newOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>  
        </el-form-item>
        <el-form-item label="性别" prop="gender" v-if="mode == 'add'">
          <el-select v-model="stuForm.gender" placeholder="请选择">
            <el-option
              v-for="item in sexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>  
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="stuForm.comment"></el-input>
        </el-form-item>
      
        <el-form-item>
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="confirmSubmitStu(stuForm)">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog :visible.sync="checkDialogVisible" width="700px" title="审核学员">
      <el-table 
        :data="checkTable" 
        ref="multipleTable"  
        height="250"
        tooltip-effect="dark" 
        @selection-change="handleSelectionChange" 
        border 
        style="width: 100%">
        <el-table-column
          type="selection"
          width="40">
        </el-table-column>
        <el-table-column prop="stuName" label="姓名"/>
        <el-table-column prop="currentGrade" label="年级">
          <template slot-scope="scope">{{ scope.row.currentGrade || '-' }}</template>
        </el-table-column>
        <el-table-column prop="fromPlace" label="籍贯">
          <template slot-scope="scope">{{ scope.row.fromPlace || '-' }}</template>
        </el-table-column>
        <el-table-column prop="parentPhone" label="家长电话">
          <template slot-scope="scope">{{ scope.row.parentPhone || '-' }}</template>
        </el-table-column>
        <el-table-column prop="isFirst" label="是否新生">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.isFirst == '1'">否</el-tag>
            <el-tag v-else>是</el-tag>
          </template>
        </el-table-column>
      
      </el-table>

      <el-row class="check-btns">
        <el-button @click="cancelCheckDialog">取消</el-button>
        <el-button type="primary" @click="confirmCheckStu(checkIds)">一键审核</el-button>
      </el-row>
    </el-dialog>


    <!-- 学员详情弹窗 -->
    <el-dialog :visible.sync="detailDialogVisible" width="600px" title="学员详情">
      <el-descriptions border>
        <el-descriptions-item label="姓名">{{detailForm.stuName || '-'}}</el-descriptions-item>
        <el-descriptions-item label="年级">{{detailForm.currentGrade || '-'}}</el-descriptions-item>
        <el-descriptions-item label="籍贯">{{detailForm.fromPlace || '-'}}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag size="small" type="success" v-if="detailForm.status == 1">已审核</el-tag>
          <el-tag size="small" type="warning" v-else-if="detailForm.status == 0">未审核</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="家长电话">{{detailForm.parentPhone || '-'}}</el-descriptions-item>
        <el-descriptions-item label="是否为新生">
          <el-tag size="small" type="success" v-if="detailForm.status == 0">是</el-tag>
          <el-tag size="small" type="warning" v-else-if="detailForm.status == 1">否</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 批量导入弹窗 -->
    <el-dialog :visible.sync="updateFileDialogVisible" width="400px" title="批量导入学员">
      <div>
        <el-upload
          class="upload-demo"
          action="/student/addBatch"
          :auto-upload="false"
          :on-change="handleChange"
          :show-file-list="true"
          accept=".xlsx,.xls"
        >
          <el-button slot="trigger" style="margin-right: 20px;">选取文件</el-button>
          <el-button type="primary" @click="submitUpload">上传</el-button>
          <div slot="tip" style="margin-top: 10px;">只能上传xls或xlsx文件，文件规范请下载模板查看</div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent , addStudent, editStudent, removeStudent, listUncheckStudent, checkStudent, updateFile} from '@/api/student';
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
export default {
  data(){
    return{
      file:null,
      mode:'add',
      currentPage:undefined,
      total:undefined,
      stuDialogVisible: false,
      checkDialogVisible:false,
      detailDialogVisible: false,
      updateFileDialogVisible: false,
      currentPage:undefined,
      total:undefined,
      sexOptions:[
        {label:'男',value:'M'},
        {label:'女',value:'F'},
      ],
      newOptions:[
        {label:'是',value:'0'},
        {label:'否',value:'1'},
      ],
      queryForm:{
        name:'',
        clazzId:'',
        pageNum:1,
        pageSize:5
      },
      checkIds:[],
      stuForm:{},
      detailForm:{},
      checkTable:[],
      tableData:[{
        activityName:'班级1',
        classDesc:'',
        name:'',
        stuName:''
      }],
      multipleSelection: []
    }
  },
  methods:{
    downlaod(){
      axios({
        method: 'POST',
        url: '/student/export/template',
        headers: {
          Authorization: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3Mzc4MzUxMzgsInVzZXJJZCI6N30.w8NRLw-2eypYd-9MuK85yXZ13z-bqIRHpCucRzqV_z8'
        },
        responseType: 'blob' // 关键设置，指定接收的响应类型为blob（二进制大对象），用于接收文件流
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] }));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'template.xlsx'); // 设置下载文件名，与后端设置的尽量一致
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }).catch((error) => {
        console.log(error);
      });
      
      
    },
    getListStu(){
      listStudent(this.queryForm).then(res=>{
        this.tableData = res.row
      }).catch(()=>{})
    },
    resetStuQuery(){
      this.queryForm = {
        name:'',
        pageNum:1,
        pageSize:5
      }
      this.getListStu()
    },
    handleEdit(data){
      this.mode = 'edit'
      this.stuDialogVisible = true
      this.stuForm = JSON.parse(JSON.stringify(data))
    },
    handleDetail(data){
      this.detailDialogVisible = true
      this.detailForm = data
    },
    handleDel(data){
      MessageBox.alert(`确定要删除教师<${data.stuName}>吗?`).then(()=>{
        removeStudent(data.id).then(res=>{
          Message.success(res.msg)
          this.getListStu()
        }).catch(()=>{})
      }).catch(()=>{})
    },
    openCheckStu(){
      this.checkDialogVisible = true
      listUncheckStudent().then(res=>{
        this.checkTable = res.data
      }).catch(()=>{})
    },
    openUpdateStu(){
      this.updateFileDialogVisible = true
    },
    cancelDialog(){
      this.stuDialogVisible = false
      this.stuForm = {}
    },
    cancelCheckDialog(){
      this.checkDialogVisible =false
      this.checkIds = []
      this.multipleSelection = []
      this.checkTable = []
    },
    openAddStuDialog(){
      this.stuDialogVisible = true
      this.mode = 'add'
    },
    confirmSubmitStu(data){
      if(this.mode == 'add'){
        data.birthday +=' 00:00:00'
        addStudent(data).then(res=>{
          Message.success(res.msg)
          this.stuDialogVisible = false
          this.stuForm = {}
          this.getListStu()
        }).catch(()=>{})
      }else if(this.mode == 'edit'){
        editStudent(data).then(res=>{
          Message.success(res.msg)
          this.stuDialogVisible = false
          this.stuForm = {}
          this.getListStu()
        }).catch(()=>{})
      }
    },
    confirmCheckStu(){
      this.checkIds = this.multipleSelection.map(e=>e.id)
      checkStudent(this.checkIds).then(res=>{
        Message.success(res.msg)
        this.checkDialogVisible =false
        this.checkIds = []
        this.multipleSelection = []
        this.checkTable = []
        this.getListStu()
      }).catch(()=>{})
    },
    handleSelectionChange(val){
      this.multipleSelection = val;
      
    },
    handleSizeChange(size){
      this.queryForm.pageSize=size
      this.getListStu(this.queryForm)
    },
    handleCurrentChange(page){
      this.queryForm.pageNum=page
      this.getListStu(this.queryForm)
    },
    

    handleChange(uploadedFile){
      this.file = uploadedFile.raw;
    },
    submitUpload(){
      const formData = new FormData();
      formData.append('file', this.file);

      updateFile(formData).then(res=>{
        Message.success(res.msg)
        this.updateFileDialogVisible = false
      }).catch(err=>{})
    },
  },
  created(){
    this.getListStu()
  }
}
</script>

<style lang="scss">
  .toolbar{
    padding: 0 10px 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-form{
      height: fit-content;
      .el-form-item{
        margin-bottom: 0;
      }
    }
  }
  .el-row::after, .el-row::before {
      display: none !important;
  }
  .check-btns{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
  }
</style>